<template>
    <!-- 主要内容区域 -->
    <div class="container mt-4">
        <!-- 工具栏 -->
        <div class="toolbar d-flex flex-wrap justify-content-between align-items-center">
            <div class="d-flex gap-2 mb-2 mb-md-0">
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#normalMessageModal" @click="selectForm(true)">
                    <i class="fas fa-paper-plane me-1"></i> 发送普通消息
                </button>
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#templateMessageModal" @click="selectForm(false)">
                    <i class="fas fa-file-invoice me-1"></i> 发送模板消息
                </button>
                <!-- <button class="btn btn-outline-danger-custom" @click="removeList" >
                    <i class="fas fa-trash-alt me-1"></i> 删除消息
                </button> -->
            </div>
            <div class="d-flex gap-2">
                <!-- <input type="text" class="form-control form-control-sm" placeholder="搜索消息标题、对象..."> -->
                <el-input
                    v-model="searchQuery"
                    style="width: 240px"
                    placeholder="标题搜索"
                    clearable
                    @click="clearTable"
                />
            </div>
        </div>
        <el-table 
            :data="filteredItems" 
            style="width: 100%" 
            :fit="true" 
            :row-style="{height:'60px'}" 
            :row-class-name="tableRowClassName"
             @selection-change="handleSelectionChange"
             >
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" fit width="100">
                <template #default="scope">{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</template>
            </el-table-column>
            <el-table-column label="发送时间" width="180">
                <template #default="scope">{{ formatTime(scope.row.sendTime) }}</template>
            </el-table-column>
            <el-table-column label="标题" fit>
                <template #default="scope">{{ scope.row.title }}</template>
            </el-table-column>
            <el-table-column label="发送对象" fit>
                <template #default="scope">{{ getGroupName(scope.row.groupIds) }}</template>
            </el-table-column>
            <el-table-column label="重要程度" width="100">
                <template #default="scope">{{ scope.row.importance }}</template>
            </el-table-column>
            <el-table-column label="状态" width="120">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleDetail(scope.row)">查看详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagine">
            <el-pagination background layout="prev, pager, next" prev-text="上一页" next-text="下一页" :pager-count="pageCount" :total="dataForm.length" @current-change="pagineChage"/>
        </div>

        <el-dialog
        v-model="dialogVisible"
        title="事务详情"
        width="50%"
        top="2%"
    >
        <hr>
        <div class="content">
            <el-scrollbar max-height="600px">
                <div class="head_content">
                    <p><strong>发布人：{{ currentUser.name }}</strong></p>
                    <p><strong>发送时间：{{ formatTime(detailData.dataForm.sendTime) }}</strong></p>
                    <p><strong>接收对象：{{ getGroupName(detailData.dataForm.groupIds) }}</strong></p>
                    <div class="status-section">
                        <h4>接收情况</h4>
                        <el-progress :percentage="(total_count-unread)/total_count*100"/>
                        <p class="progress-text">
                            已接收 <strong id="modal-received-count">{{ total_count-unread }}</strong> / 
                            <span id="modal-total-count">{{ total_count }}</span> 人 
                        </p>
                    </div>
                </div>
                <hr>
                <div class="main_content">
                    <h5>通知正文</h5>
                    <p>{{ content }}</p>
                    <h5><strong>一、时间</strong></h5>
                    <p>{{ time }}</p>
                    <h5><strong>二、地点</strong></h5>
                    <p>{{ location }}</p>
                    <div class="attachments-section">
                       <h5>附件</h5>
                        <ul class="attachment-list" v-if="detailData.dataForm.file.fileName!=null||detailData.dataForm.file.excelName!=null">
                           <li v-if="detailData.dataForm.file.fileName!=null">
                            <span class="file-info">
                            <i>📄</i> {{ detailData.dataForm.file.fileName }} (2.5MB)
                            </span>
                            <a :href="fileUrl" target="_blank" download>下载</a>
                           </li> 
                           <li v-if="detailData.dataForm.file.excelName!=null">
                            <span class="file-info">
                            <i>📄</i> {{ detailData.dataForm.file.excelName }} (2.5MB)
                            </span>
                            <a :href="excelUrl" target="_blank" download>下载</a>
                           </li> 
                           
                        </ul> 
                        <p v-else>无附件</p>
                    </div>
                    <div class="record_content">
                        <div class="reply-details-section">
    
                            <h4 style="font-size: 16px; font-weight: 600; margin-bottom: 16px; color: #333;">处理回复</h4>
                            <div v-if="handleStatus.records.length==0">暂无处理消息</div>
                            <ul class="reply-list" v-else>
                                <li class="reply-item" v-for="item in handleStatus.records" :key="item.id">
                                    <div class="reply-header">
                                        <div class="replier-info">
                                            <strong style="font-size: 14px; color: #333;">{{ getNameById(item.processorUserId) }}</strong>
                                            <span class="status-badge status-completed">已处理</span>
                                        </div>
                                        <span class="reply-time" style="font-size: 12px; color: #999;">{{ formatTime(item.processTime) }}</span>
                                    </div>
                                    <div class="reply-content" style="margin-bottom: 10px;">
                                        <p style="font-size: 14px; color: #666; margin: 0;">{{ item.processInfo }}</p>
                                    </div>
                                    <div class="reply-attachments" v-if="item.attachmentFilename!=null">
                                        <div class="attachment-item">
                                            <div>
                                                <span class="file-icon" style="margin-right: 8px;">📎</span> 
                                                <span class="file-name">t_file.sql</span>
                                                <span class="file-size" style="color: #999; margin-left: 8px;">(2.5MB)</span>
                                            </div>
                                            <a :href="`/api/message/getRecordFile/${ item.recordId }`" class="download-link" style="color: #1890ff; text-decoration: none;">下载</a>
                                        </div>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                    
                </div>
            </el-scrollbar>
            
        </div>
        <!-- 3. 弹窗底部操作栏 -->
        <div class="modal-footer">
            <!-- <button class="btn btn-secondary">编辑</button> -->
            <!-- <button class="btn btn-danger">撤回</button> -->
            <button class="btn btn-primary" @click="dialogVisible=false">关闭</button>
        </div>
    </el-dialog>
    </div>
</template>
<script setup>
import { ref,reactive, computed, toRefs, onMounted, onUnmounted } from 'vue';
import { useMessageStore } from '@/stores/Message';
import { useRouter } from 'vue-router' // 1. 引入 useRouter
import { Modal } from 'bootstrap/dist/js/bootstrap.bundle.min';
import { format, parseISO } from 'date-fns';

const router = useRouter() // 2. 获取 router 实例
const messageStore = useMessageStore()  // 状态
const pageSize = ref(10)    // 页面大小
const pageCount = ref(5)   // 页数
const currentPage = ref(1)
const dialogVisible = ref(false)    // 弹窗
const removeItems = reactive([])  // 删除列表
const currentUser = ref();
// ==========
// 详情数据
const detailData = reactive({
    dataForm:null
})

const excelUrl = computed(()=>{
    return "/api/message/getExcel/"+detailData.dataForm.file.messageId
})
const fileUrl = computed(()=>{
    return "/api/message/getFile/"+detailData.dataForm.file.messageId
})

const location = computed(()=>{
    const match = detailData.dataForm.messageChild.templateContent.match(/，\n    地点：(.*)\n$/);
    // console.log(match);
    return match ? match[1].trim() : null;
})
const content = computed(()=>{
    const match = detailData.dataForm.messageChild.templateContent.match(/详情：(.*?)，\n    时间/);
    return match ? match[1].trim() : null;
})
const time = computed(()=>{
    const match = detailData.dataForm.messageChild.templateContent.match(/时间：(.*?)，\n    地点/);
    return match ? match[1].trim() : null;
})

// 状态
const handleStatus = reactive({
    status: null,
    records:null,
    member:null
})
const total_count = computed(()=>{
    return handleStatus.status.total_count
})
const unread = computed(()=>{
    return handleStatus.status.unread
})

// 根据组号获取组名
const getGroupName = (data)=>{
     if (!data || data.length === 0) {
        return ''; // 如果传入的是 undefined, null, 或空数组，返回一个空字符串
    }
    const groupMap = new Map(messageStore.Group);
    // console.log(groupMap);
    
    const groupNames = data.map(id => {
        return groupMap.get(id); 
    });
    // console.log(groupNames);
    // return 
    return groupNames.join('，');
    
}

// 获取名字根据id
const getNameById = (data)=>{
    // console.log(handleStatus.member.filter(item=>item.userId==10000006));
    
    const member = handleStatus.member.filter(item=>item.userId===data.toString())
    // console.log(member[0].userName);
    
    return member[0].userName
}

// ==========
const dataForm = computed(()=> messageStore.ListItem)
// console.log(dataForm.value.length);


const tableData = reactive({
    form:dataForm
})


const list = computed(()=>{
    return tableData.form.slice(0+(currentPage.value-1)*pageSize.value,pageSize.value+(currentPage.value-1)*pageSize.value)    
})

// 时间格式化
const formatTime = (time) => {
    
    // return format(parseISO(time), 'yyyy-MM-dd HH:mm:ss');
    // 同样进行防御性判断
  if (!time) {
    return '---';
  }
  
  try {
    // 2. 使用 parseISO 解析字符串，它比 new Date() 更严格和安全
    const date = parseISO(time);
    // 3. 使用 format 函数直接格式化，模板字符串非常直观
    return format(date, 'yyyy-MM-dd HH:mm:ss');
  } catch (error) {
    // 如果传入的字符串格式异常，防止页面崩溃
    console.error("日期格式化失败: ", time, error);
    return time; // 返回原始字符串作为备用
  }
}

// 搜索查询
const searchQuery = ref();

// 计算属性：过滤后的列表
const filteredItems = computed(() => {
    // console.log("data=>");
    // console.log(list.value);
    
    
    const query = searchQuery.value?.toLowerCase();
    if (!query) {
        // console.log(list.value.length);
        
        return list.value; // 如果没有搜索查询，返回所有项目
    }
    return dataForm.value.filter(item => {
        // 使用正则表达式进行模糊搜索
        const regex = new RegExp(query.split('').join('.*'), 'i')
        return regex.test(item.title)
    });
});

//------------------------
// 表格样式
const tableRowClassName = ({row,rowIndex}) => {
  if (rowIndex % 2 == 1) {
    return 'warning-row'
  }
  return ''
}

// 表格选择框
const selectForm = (val) => {
    if(val) return router.push("/send/0")
    else return router.push("/send/1")
}

// 处理详情
const handleDetail = async (row)=>{
    
    detailData.dataForm = row
    handleStatus.status = await messageStore.HandleStatus(detailData.dataForm.id).then(res=>{
        return res.data
    })
    handleStatus.records = await messageStore.HandleRecord(detailData.dataForm.id).then(res=>res.data)
    handleStatus.member = await messageStore.HandleMember(detailData.dataForm.groupIds).then(res=>res.data)
    dialogVisible.value = true
    
    // console.log("==============>");
    // console.log(detailData.dataForm.groupIds);    
    
}

// 页数更改
const pagineChage = (number)=>{
    currentPage.value = number
}


// 处理选择框
const handleSelectionChange = (val)=>{
    removeItems.length = 0;  // 清空数组
    removeItems.push(...val.map(item => item.id))
}

// 删除数据
const removeList = ()=>{
    messageStore.HandleGroups(10000001)
    console.log("group====>");
    
    console.log(messageStore.GroupList);
    
    // messageStore.removeItem(removeItems)
    // return ElMessage({
    //     message: 'Congrats, this is a success message.',
    //     type: 'success',
    // })
}

// 清空
const clearTable = ()=>{

}

onMounted(()=>{
    
    // 从 localStorage 中获取存储的用户信息字符串
  const userInfoString = localStorage.getItem('userInfo');


  if (userInfoString) {
    // 将 JSON 字符串解析回 JavaScript 对象
    const userInfo = JSON.parse(userInfoString);
    currentUser.value = userInfo
    console.log(currentUser);
    
    // 检查 userId 是否有效，然后发起请求
    if (userInfo.userId) {
        messageStore.get();
        messageStore.HandleGroups(userInfo.userId);
    } else {
      console.error("在 localStorage 中找到了 userInfo但缺少 userId！");
    }
  } else {
    // 处理用户未登录的情况
    console.error("未在 localStorage 中找到用户信息，用户可能未登录。");
  }
})
</script>

<style scoped>
.reply-details-section {
    margin-top: 24px; 
    padding-top: 20px; 
    border-top: 1px solid #e8e8e8;
}
.reply-list {
    list-style: none;
    padding: 0;
    margin: 0;
}
.reply-item {
    margin-bottom: 20px; 
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f0f0;
}
.reply-header {
    display: flex; 
    justify-content: space-between; 
    align-items: center;
    margin-bottom: 8px;
}
.replier-info {
    display: flex; 
    align-items: center;
}
.status-completed {
    background-color: #e6f7ff; 
    border: 1px solid #91d5ff; 
    color: #1890ff; 
    font-size: 12px; 
    padding: 2px 8px; 
    border-radius: 4px; 
    margin-left: 10px;
}
.attachment-item {
    background-color: #fafafa; 
    padding: 8px 12px; 
    border-radius: 4px; 
    display: flex; 
    align-items: center; 
    justify-content: space-between;
}
/* 附件 */
.attachments-section {
    margin-top: 20px;
}
.attachment-list {
    list-style: none;
    padding: 0;
    margin: 0;
}
.attachment-list li {
    background-color: #f8f9fa;
    border: 1px solid #dee2e6;
    padding: 10px 15px;
    border-radius: 5px;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.attachment-list a {
    color: #007bff;
    text-decoration: none;
    font-weight: bold;
}
.attachment-list .file-info {
    font-size: 14px;
    color: #6c757d;
}
.attachment-list .file-info i {
    margin-right: 8px; /* 假设使用FontAwesome等图标库 */
}


.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
/* 底部按钮 */
.modal-footer {
    border-top: 1px solid #e9ecef;
    padding-top: 15px;
    text-align: right;
}
.btn {
    padding: 8px 20px;
    border: 1px solid transparent;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    margin-left: 10px;
    transition: all 0.2s;
}
.btn-primary { color: #fff; background-color: #007bff; border-color: #007bff; }
.btn-secondary { color: #fff; background-color: #6c757d; border-color: #6c757d; }
.btn-danger { color: #fff; background-color: #dc3545; border-color: #dc3545; }

.btn:hover { opacity: 0.8; }


/* 基础与布局 (直接作用于模板中的类) */
.container {
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  padding: 0 1rem;
}
.mt-4 {
  margin-top: 1.5rem;
}
.d-flex {
  display: flex;
}
.flex-wrap {
  flex-wrap: wrap;
}
.justify-content-between {
  justify-content: space-between;
}
.align-items-center {
  align-items: center;
}
.gap-2 {
  gap: 0.75rem;
}
.mb-2 {
  margin-bottom: 0.5rem;
}
@media (min-width: 768px) {
  .mb-md-0 {
    margin-bottom: 0;
  }
}
.me-1 {
  margin-right: 0.25rem;
}

/* 工具栏样式 (模仿 .filter-section) */
.toolbar {
  background-color: white;
  padding: 1rem 1.5rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.07);
}

/* 按钮样式 (作用于模板中的 .btn 类) */
.btn {
  display: inline-flex;
  align-items: center;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 500;
  border: 1px solid transparent;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
}
.btn.btn-sm {
    padding: 0.4rem 0.8rem;
    font-size: 0.75rem;
}
.btn-primary { background-color: #3b82f6; color: white; }
.btn-primary:hover { background-color: #2563eb; }
.btn-success { background-color: #10b981; color: white; }
.btn-success:hover { background-color: #059669; }
/* 注意这里是模板中自定义的类名 */
.btn-outline-danger-custom { background-color: transparent; color: #ef4444; border-color: #fca5a5; }
.btn-outline-danger-custom:hover { background-color: #fee2e2; }
.btn-outline-secondary { background-color: transparent; color: #6b7280; border-color: #d1d5db; }
.btn-outline-secondary:hover { background-color: #f3f4f6; }

/* Element Plus 表格深度样式覆盖 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.07);
}
:deep(.el-table th.el-table__cell) {
  background-color: #f9fafb !important;
  color: #374151;
  font-weight: 600;
}
:deep(.el-table tr:hover > td.el-table__cell) {
  background-color: #f9fafb !important;
}
/* 修改表格中的 "查看详情" 按钮样式 */
:deep(.el-table .el-button--primary) {
  background-color: #eef2ff !important;
  color: #3b82f6 !important;
  border-color: #dbeafe !important;
  font-weight: 500;
  transition: all 0.2s;
}
:deep(.el-table .el-button--primary:hover) {
  background-color: #dbeafe !important;
}

/* 分页容器 */
.pagine {
  display: flex;
  justify-content: flex-end;
  margin-top: 1.5rem;
}
/* Element Plus 分页深度样式覆盖 */
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled)) {
  border-radius: 4px;
}
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #3b82f6;
}
:deep(.el-pagination.is-background .btn-prev),
:deep(.el-pagination.is-background .btn-next) {
  border-radius: 4px;
}

/* Element Plus 对话框深度样式覆盖 */
:deep(.el-dialog__footer .el-button--primary) {
  background-color: #3b82f6;
  border-color: #3b82f6;
}
:deep(.el-dialog__footer .el-button--primary:hover) {
  background-color: #2563eb;
  border-color: #2563eb;
}
</style>
